#!/usr/bin/env python3
"""
hosts文件修改工具 - 将m.dadefeng.com指向本地测试服务器
"""

import subprocess
import sys
import os

def backup_hosts_file():
    """备份hosts文件"""
    hosts_path = '/etc/hosts'
    backup_path = '/etc/hosts.backup'
    
    try:
        subprocess.run(['sudo', 'cp', hosts_path, backup_path], check=True)
        print("✅ hosts文件已备份")
        return True
    except subprocess.CalledProcessError:
        print("❌ 备份hosts文件失败，请检查sudo权限")
        return False

def add_host_entry():
    """添加hosts条目"""
    entry = "127.0.0.1 m.dadefeng.com"
    
    try:
        # 检查是否已存在该条目
        result = subprocess.run(['grep', '-n', 'm.dadefeng.com', '/etc/hosts'], 
                              capture_output=True, text=True)
        
        if result.returncode == 0:
            print("⚠️  m.dadefeng.com 条目已存在")
            return True
        
        # 添加新条目
        echo_cmd = subprocess.Popen(['echo', entry], stdout=subprocess.PIPE)
        sudo_cmd = subprocess.Popen(['sudo', 'tee', '-a', '/etc/hosts'], 
                                   stdin=echo_cmd.stdout, stdout=subprocess.PIPE)
        sudo_cmd.communicate()
        
        print("✅ 已添加hosts条目: 127.0.0.1 m.dadefeng.com")
        return True
        
    except Exception as e:
        print(f"❌ 添加hosts条目失败: {e}")
        return False

def remove_host_entry():
    """移除hosts条目"""
    try:
        # 使用sed删除包含m.dadefeng.com的行
        subprocess.run(['sudo', 'sed', '-i', '/m.dadefeng.com/d', '/etc/hosts'], check=True)
        print("✅ 已移除m.dadefeng.com hosts条目")
        return True
    except subprocess.CalledProcessError:
        print("❌ 移除hosts条目失败")
        return False

def flush_dns():
    """刷新DNS缓存"""
    try:
        # Linux系统刷新DNS
        subprocess.run(['sudo', 'systemd-resolve', '--flush-caches'], check=True)
        print("✅ DNS缓存已刷新")
    except subprocess.CalledProcessError:
        try:
            # 尝试其他方法
            subprocess.run(['sudo', 'service', 'network-manager', 'restart'], check=True)
            print("✅ 网络服务已重启")
        except subprocess.CalledProcessError:
            print("⚠️  无法自动刷新DNS，请手动重启网络服务")

def show_hosts_status():
    """显示hosts文件状态"""
    try:
        result = subprocess.run(['grep', '-n', 'm.dadefeng.com', '/etc/hosts'], 
                              capture_output=True, text=True)
        
        if result.returncode == 0:
            print("📋 当前hosts配置:")
            print(result.stdout)
        else:
            print("📋 m.dadefeng.com 未在hosts文件中配置")
    except Exception as e:
        print(f"❌ 检查hosts状态失败: {e}")

def main():
    if len(sys.argv) < 2:
        print("用法:")
        print("  python3 hosts_setup.py add     # 添加hosts条目")
        print("  python3 hosts_setup.py remove  # 移除hosts条目")
        print("  python3 hosts_setup.py status  # 查看当前状态")
        print("  python3 hosts_setup.py backup  # 备份hosts文件")
        return
    
    command = sys.argv[1].lower()
    
    if command == 'add':
        if backup_hosts_file() and add_host_entry():
            flush_dns()
            print("\n🎉 设置完成！现在可以访问 http://m.dadefeng.com:8080/")
            print("📱 测试URL: http://m.dadefeng.com:8080/?muserid=1959618590952931330&buserid=1923370414273716226&flag=Y")
    
    elif command == 'remove':
        if remove_host_entry():
            flush_dns()
            print("\n🎉 hosts条目已移除")
    
    elif command == 'status':
        show_hosts_status()
    
    elif command == 'backup':
        backup_hosts_file()
    
    else:
        print(f"❌ 未知命令: {command}")

if __name__ == '__main__':
    main()